package com.wn.ticket.web;

import com.bestvike.linq.Linq;
import com.wn.ticket.common.ResponseEntity;
import com.wn.ticket.entity.Coupon;
import com.wn.ticket.entity.Notice;
import com.wn.ticket.entity.User;
import com.wn.ticket.entity.UserCoupon;
import com.wn.ticket.service.UserCouponService;
import com.wn.ticket.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/front/userCoupon")
public class UserCouponController {
    @Autowired
    private UserCouponService userCouponService;


    @RequestMapping("/add")
    public ResponseEntity add(@RequestBody UserCoupon userCoupon) {

        List<UserCoupon> userCouponList = userCouponService.getByUserId(userCoupon.getUser().getId());
//        try {
        //判断条件下获取最后一条数据
        UserCoupon userCouponLast = Linq.of(userCouponList).where(x -> x.getCoupon().getId() == userCoupon.getCoupon().getId()).lastOrDefault();
        if (userCouponLast != null) {
            //数量加1；
            userCouponLast.setNumber(userCouponLast.getNumber() + 1);

            userCouponService.UCupdate(userCouponLast);
        } else {
            //添加优惠券映射，数量默认为1
            userCouponLast.setNumber(1);
            userCouponService.add(userCoupon);
        }
        return ResponseEntity.success;
//        } catch (Exception ex) {
//            return new ResponseEntity("400", ex.getMessage(), null);
//        }
    }

    @RequestMapping("/getByUserId")
    public ResponseEntity getByUserId(int userId) {
        List<UserCoupon> list = userCouponService.getByUserId(userId);
        List<UserCoupon> userCouponList = Linq.of(list).where(x -> x.getNumber() > 0).toList();
        return new ResponseEntity(userCouponList);
    }

    @RequestMapping("/del")
    public ResponseEntity del(int userId, int couponId) {
        userCouponService.del(userId, couponId);
        return ResponseEntity.success;
    }

    @RequestMapping("/use")
    public ResponseEntity use(UserCoupon userCoupon) {
        userCoupon.setNumber(userCoupon.getNumber() - 1);
        userCouponService.UCupdate(userCoupon);
        return ResponseEntity.success;
    }

}
